<template>
  <div class='role'>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="javascript:;">权限管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-button type="success" plain @click="addRoleFormVisible=true">添加角色</el-button>
    <template>
      <el-table :data="UserRolesList" style="width: 100%">
        <el-table-column type="expand">
          <!-- 展开行 -->
          <template slot-scope="scope">
            <!-- first 最外层 -->
            <el-row v-if="scope.row.children.length!==0" :gutter="20" type="flex" v-for='first in scope.row.children' :key='first.id' style='margin-bottom:15px;'>
              <el-col :span="4">
                <div class="grid-content bg-purple">
                  <el-tag closable @close='deleteroleright(scope.row,first.id)'>
                    {{first.authName}}
                  </el-tag>
                </div>
              </el-col>
              <!-- 箭头 判断下一层有没有数据，没有则不显示箭头-->
              <el-col v-if="first.children.length!==0" :span="2" style='margin-top:8px;'>
                <span class="el-icon-arrow-right"></span>
              </el-col>
              <!-- second 第二层 -->
              <el-col :span="18">
                <el-row :gutter="20" type="flex" v-for='second in first.children' :key='second.id' style='margin-bottom:15px;'>
                  <el-col :span="4">
                    <div class="grid-content bg-purple">
                      <el-tag closable type='success' @close='deleteroleright(scope.row,second.id)'>
                        {{second.authName}}
                      </el-tag>
                    </div>
                  </el-col>
                  <!-- 箭头 -->
                  <el-col v-if="second.children.length!==0" :span="1" style='margin-top:8px;'>
                    <span class="el-icon-arrow-right"></span>
                  </el-col>
                  <!-- three 第三层 -->
                  <el-col :span="19">
                    <div class="grid-content bg-purple">
                      <el-tag closable type='info' @close='deleteroleright(scope.row,three.id)' v-for='three in second.children' :key='three.id' style='margin-right:15px;margin-bottom:15px'>
                        {{three.authName}}
                      </el-tag>
                    </div>
                  </el-col>
                </el-row>
              </el-col>

            </el-row>
            <el-row v-if="scope.row.children.length===0">
              <el-col style=" text-align: center;">没有权限噢,
                <el-button @click="grantVisible=true">请前往添加</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="描述" width="180">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button type="info" icon="el-icon-edit" plain></el-button>
            </el-tooltip>
            <el-tooltip content="授权角色" placement="top">
              <el-button type="warning" @click="showGrantDialog(scope.row)" icon="el-icon-share" plain></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" plain></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 权限分配 -->
    <el-dialog title="分配权限" :visible.sync="grantVisible">
      <div style="height:300px;overflow:auto">
        <el-tree :data="allRightsRole" show-checkbox node-key="id" :default-expand-all='true' :default-checked-keys="checkedkeys" ref="tree" :props="defaultProps">
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="hiddenGrantDialog">取 消</el-button>
        <el-button type="primary" @click="grantDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog title="收货地址" :visible.sync="addRoleFormVisible">
      <el-form :model="addRoleForm" :rules="rules" ref="addrole">
        <el-form-item label="活动名称" :label-width="formLabelWidth" prop='roleName'>
          <el-input v-model="addRoleForm.roleName" auto-complete="off" ></el-input>
        </el-form-item>
        <el-form-item label="活动名称" :label-width="formLabelWidth" prop='roleDesc'>
          <el-input v-model="addRoleForm.roleDesc" auto-complete="off" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserRolesList,
  delroleright,
  getAllRights,
  grantroleright,
  addRole
} from '@/api/index.js'
export default {
  data () {
    return {
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          {}
        ]
      },
      formLabelWidth: '120px',
      addRoleFormVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      roleid: '',
      // 被选中的id值
      checkedkeys: [],
      UserRolesList: [],
      grantVisible: false,
      allRightsRole: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  mounted () {
    this.init()
    // 加载树状角色权限
    getAllRights('tree').then(res => {
      console.log('----------------')
      console.log(res)
      this.allRightsRole = res.data
    })
  },
  methods: {
    // 添加角色
    addRoleSubmit () {
      addRole(this.addRoleForm).then(res => {
        console.log(res)
        if (res.meta.status === 201) {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
        // 页面数据刷新
        this.init()
        // 表单内容刷新
        this.$refs['addrole'].resetFields()
        this.addRoleFormVisible = false
      })
    },
    // 加载首页角色权限
    init () {
      getUserRolesList().then(res => {
        console.log(res)
        this.UserRolesList = res.data
      })
    },
    deleteroleright (row, rightid) {
      delroleright(row.id, rightid).then(res => {
        console.log(res)
        if (res.meta.status === 200) {
          row.children = res.data
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
      })
    },
    // 点击授权按钮
    showGrantDialog (row) {
      this.grantVisible = true
      // 存储roleId为后面提交做准备
      this.roleid = row.id
      // 重置checkedkeys数组
      this.checkedkeys.length = 0
      row.children.forEach(first => {
        if (first.children && first.children.length !== 0) {
          first.children.forEach(second => {
            if (second.children && second.children.length !== 0) {
              second.children.forEach(three => {
                this.checkedkeys.push(three.id)
              })
            }
          })
        }
      })
      console.log(this.checkedkeys)
    },
    // 清空选项框
    resetChecked () {
      this.$refs.tree.setCheckedKeys([])
    },
    // 取消授权对话框
    hiddenGrantDialog () {
      this.grantVisible = false
      this.resetChecked()
    },
    // 为指定角色授权
    grantDialogSubmit () {
      // 这种方法无法获取最底层的id值
      //   var checks = this.$refs.tree.getCheckedKeys()
      //   console.log(checks)
      // 这种方法pid会重复，后期发送请求需要处理
      var node = this.$refs.tree.getCheckedNodes()
      //   console.log(node)
      // 使用map方法遍历node对象
      var nodearr = node.map(value => {
        return value.id + ',' + value.pid
      })
      //   console.log(nodearr)
      // 转换成字符串以逗号分隔
      var strarr = nodearr.join(',')
      //   console.log(strarr)
      // 去重复 首先需要把字符串转换成数组
      var ridsarr = strarr.split(',')
      //   console.log(ridsarr)
      // 去重复使用es6 Set方法
      //   var tempSet2 = new Set(ridsarr)
      //   console.log(tempSet2)
      var tempSet = [...new Set(ridsarr)]
      //   var final = Array.from(tempSet)
      console.log(tempSet)
      //   console.log(final)
      var rids = tempSet.join(',')
      grantroleright({ roleid: this.roleid, rids: rids }).then(res => {
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.meta.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: res.meta.msg
          })
        }
        // 这里需要重新获取角色列表,因为这样才能更新到data里面数据源UserRolesList,从而点击授权按钮的时候，显示最新权限信息，因为数据源变化,scope.row也会发生改变
        this.init()
        this.grantVisible = false
        // 重置树状图的信息
        this.resetChecked()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  background-color: #f5f5f5;
  height: 45px;
  font-size: 15px;
  padding-left: 10px;
  line-height: 45px;
  margin-bottom: 15px;
}
</style>
